package com.longcai.cm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.longcai.cm.dao.JaOrderCommentMapper;
import com.longcai.cm.dao.JaShopMapper;
import com.longcai.cm.domain.JaOrderComment;
import com.longcai.cm.domain.JaShop;
import com.longcai.cm.exception.SysRuntimeException;
import com.longcai.cm.service.JaShopService;
import com.longcai.cm.base.service.BaseServiceImpl;
import org.springframework.stereotype.Service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;


/**
 * @author LBX
 */
@Service
public class JaShopServiceImpl extends BaseServiceImpl<JaShop> implements JaShopService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private JaOrderCommentMapper orderCommentMapper;

    @Resource
    private JaShopMapper shopMapper;

    @Override
    public void insertPoint(String lng, String lat, String id) {
        final boolean flag = lambdaUpdate()
                .eq(JaShop::getId, id)
                .setSql("location = POINT (" + lng + ", " + lat + ")")
                .update();
        if (!flag) {
            throw new SysRuntimeException("Position Save Error!");
        }
    }

    /**
     * @param shop 门店
     */
    @Override
    public void updateComment(JaShop shop) {
        final JaOrderComment comment = orderCommentMapper.selectOne(
                new QueryWrapper<JaOrderComment>()
                        .select("sum(shop_score + service_score + quality_score) as shop_score ")
                        .eq("shop_id", shop.getId())
        );
        final Long count = orderCommentMapper.selectCount(
                new LambdaQueryWrapper<JaOrderComment>()
                        .eq(JaOrderComment::getShopId, shop.getId())
        );
        shop.setCommentCount(count);
        shop.setScore(new BigDecimal(comment.getShopScore()).divide(new BigDecimal(count * 3), 1, RoundingMode.HALF_UP).intValue() );
        shopMapper.updateById(shop);
    }
}
